import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Tag,
  Popconfirm,
  Card,
  Row,
  Col
} from 'antd';
import { 
  PlusOutlined, 
  PlayCircleOutlined, 
  StopOutlined, 
  RollbackOutlined,
  EyeOutlined 
} from '@ant-design/icons';
import api from '../services/authService';

const { Option } = Select;

interface Deployment {
  id: number;
  name: string;
  version: string;
  status: string;
  deployment_type: string;
  application_name: string;
  environment_name: string;
  creator_name: string;
  started_at: string;
  completed_at: string;
  created_at: string;
}

const Deployments: React.FC = () => {
  const [deployments, setDeployments] = useState<Deployment[]>([]);
  const [applications, setApplications] = useState([]);
  const [environments, setEnvironments] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [logsModalVisible, setLogsModalVisible] = useState(false);
  const [selectedDeployment, setSelectedDeployment] = useState<Deployment | null>(null);
  const [logs, setLogs] = useState('');
  const [form] = Form.useForm();

  useEffect(() => {
    fetchDeployments();
    fetchApplications();
    fetchEnvironments();
  }, []);

  const fetchDeployments = async () => {
    setLoading(true);
    try {
      const response = await api.get('/deployments/');
      setDeployments(response.data);
    } catch (error) {
      message.error('获取部署列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchApplications = async () => {
    try {
      const response = await api.get('/applications/');
      setApplications(response.data);
    } catch (error) {
      console.error('获取应用列表失败:', error);
    }
  };

  const fetchEnvironments = async () => {
    try {
      const response = await api.get('/environments/');
      setEnvironments(response.data);
    } catch (error) {
      console.error('获取环境列表失败:', error);
    }
  };

  const handleCreate = () => {
    form.resetFields();
    setModalVisible(true);
  };

  const handleStart = async (id: number) => {
    try {
      await api.post(`/deployments/${id}/start`);
      message.success('部署已启动');
      fetchDeployments();
    } catch (error) {
      message.error('启动部署失败');
    }
  };

  const handleStop = async (id: number) => {
    try {
      await api.post(`/deployments/${id}/stop`);
      message.success('部署已停止');
      fetchDeployments();
    } catch (error) {
      message.error('停止部署失败');
    }
  };

  const handleRollback = async (id: number) => {
    try {
      await api.post(`/deployments/${id}/rollback`);
      message.success('回滚已启动');
      fetchDeployments();
    } catch (error) {
      message.error('回滚失败');
    }
  };

  const handleViewLogs = async (deployment: Deployment) => {
    setSelectedDeployment(deployment);
    try {
      const response = await api.get(`/deployments/${deployment.id}/logs`);
      setLogs(response.data.logs || '');
    } catch (error) {
      setLogs('获取日志失败');
    }
    setLogsModalVisible(true);
  };

  const handleSubmit = async (values: any) => {
    try {
      await api.post('/deployments/', values);
      message.success('创建成功');
      setModalVisible(false);
      fetchDeployments();
    } catch (error) {
      message.error('创建失败');
    }
  };

  const getStatusColor = (status: string) => {
    const colors: { [key: string]: string } = {
      pending: 'orange',
      running: 'blue',
      success: 'green',
      failed: 'red',
      cancelled: 'gray'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: { [key: string]: string } = {
      pending: '等待中',
      running: '运行中',
      success: '成功',
      failed: '失败',
      cancelled: '已取消'
    };
    return texts[status] || status;
  };

  const columns = [
    {
      title: '部署名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '应用',
      dataIndex: 'application_name',
      key: 'application_name',
    },
    {
      title: '环境',
      dataIndex: 'environment_name',
      key: 'environment_name',
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '部署类型',
      dataIndex: 'deployment_type',
      key: 'deployment_type',
      render: (type: string) => (
        <Tag>{type.toUpperCase()}</Tag>
      ),
    },
    {
      title: '创建者',
      dataIndex: 'creator_name',
      key: 'creator_name',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: Deployment) => (
        <Space>
          {record.status === 'pending' && (
            <Button 
              type="link" 
              icon={<PlayCircleOutlined />}
              onClick={() => handleStart(record.id)}
            >
              启动
            </Button>
          )}
          {(record.status === 'running' || record.status === 'pending') && (
            <Button 
              type="link" 
              icon={<StopOutlined />}
              onClick={() => handleStop(record.id)}
            >
              停止
            </Button>
          )}
          <Button 
            type="link" 
            icon={<RollbackOutlined />}
            onClick={() => handleRollback(record.id)}
          >
            回滚
          </Button>
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => handleViewLogs(record)}
          >
            日志
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h1>部署管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          创建部署
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={deployments}
        loading={loading}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title="创建部署"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="部署名称"
            rules={[{ required: true, message: '请输入部署名称' }]}
          >
            <Input placeholder="请输入部署名称" />
          </Form.Item>

          <Form.Item
            name="version"
            label="版本"
            rules={[{ required: true, message: '请输入版本' }]}
          >
            <Input placeholder="请输入版本" />
          </Form.Item>

          <Form.Item
            name="application_id"
            label="应用"
            rules={[{ required: true, message: '请选择应用' }]}
          >
            <Select placeholder="请选择应用">
              {applications.map((app: any) => (
                <Option key={app.id} value={app.id}>
                  {app.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="environment_id"
            label="环境"
            rules={[{ required: true, message: '请选择环境' }]}
          >
            <Select placeholder="请选择环境">
              {environments.map((env: any) => (
                <Option key={env.id} value={env.id}>
                  {env.display_name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="deployment_type"
            label="部署类型"
            rules={[{ required: true, message: '请选择部署类型' }]}
          >
            <Select placeholder="请选择部署类型">
              <Option value="rolling">滚动更新</Option>
              <Option value="blue_green">蓝绿部署</Option>
              <Option value="canary">金丝雀发布</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`部署日志 - ${selectedDeployment?.name}`}
        open={logsModalVisible}
        onCancel={() => setLogsModalVisible(false)}
        footer={null}
        width={800}
      >
        <pre style={{ 
          background: '#f5f5f5', 
          padding: '16px', 
          borderRadius: '4px',
          maxHeight: '400px',
          overflow: 'auto'
        }}>
          {logs}
        </pre>
      </Modal>
    </div>
  );
};

export default Deployments;
